package com.chj.security;

import javax.annotation.PostConstruct;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.oauth2.config.annotation.builders.InMemoryClientDetailsServiceBuilder;
import org.springframework.security.oauth2.provider.ClientDetails;
import org.springframework.security.oauth2.provider.ClientDetailsService;
import org.springframework.security.oauth2.provider.ClientRegistrationException;
import org.springframework.stereotype.Component;

@Component("myClientDetailsService")
public class MyClientDetailService implements ClientDetailsService {

	Logger logger = LoggerFactory.getLogger(MyClientDetailService.class);

	private ClientDetailsService clientDetailsService;

	@PostConstruct
	public void init() {
		InMemoryClientDetailsServiceBuilder inMemoryClientDetailsServiceBuilder = new InMemoryClientDetailsServiceBuilder();
		inMemoryClientDetailsServiceBuilder
		.withClient("app1")
		.secret("app")
		.authorizedGrantTypes("client_credentials", "password", "refresh_token")
		.resourceIds("test-resource01")
		.scopes("read", "write")
		.and()
		.withClient("app2")
		.secret("app")
		.authorizedGrantTypes("client_credentials", "password", "refresh_token")
		.resourceIds("test-resource01", "oauth2-resource")
		.scopes("read", "write")
		.and()
		.withClient("app3")
		.secret("app")
		.authorizedGrantTypes("client_credentials", "password", "refresh_token")
		.resourceIds("test-resource", "oauth2-resource")
		.scopes("read", "write")
		.and()
		.withClient("app4")
		.secret("app")
		.authorizedGrantTypes("client_credentials", "password", "refresh_token")
		.resourceIds("oauth2-resource", "test-resource", "test-resource01")
		.scopes("read", "write")
		.and()
		.withClient("wechat")
		.secret("wechat")
		.authorizedGrantTypes("password", "refresh_token")
		.resourceIds("test-resource", "oauth2-resource")
		.scopes("read", "write")
		.and()
		.withClient("web")
		.secret("web")
		.authorizedGrantTypes("authorization_code", "password", "refresh_token")
		.resourceIds("test-resource", "oauth2-resource")
		.scopes("client");
		try {
			clientDetailsService = inMemoryClientDetailsServiceBuilder.build();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	@Override
	public ClientDetails loadClientByClientId(String clientId) throws ClientRegistrationException {
		logger.info("----------------------loadClientByClientId --> clientId = " + clientId);
		ClientDetails clientDetails = clientDetailsService.loadClientByClientId(clientId);
		logger.info("----------------------loadClientByClientId --> clientDetails = " + clientDetails.getClientSecret());
		return clientDetails;
	}
}
